package com.manor.main.fragment

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.manor.common.utils.*
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.*
import com.bumptech.glide.Glide
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.manor.common.CommonAppConfig
import com.manor.common.Constants
import com.manor.common.activity.AbsActivity
import com.manor.common.em.AuthType
import com.manor.common.interfaces.CommonCallback
import com.manor.common.interfaces.ImageResultCallback
import com.manor.im.activity.HChatRoomActivity
import com.manor.im.activity.HMsgActivity
import com.manor.im.http.ImHttpUtil
import com.manor.main.R
import com.manor.main.activity.*
import com.manor.main.adapter.MianPersonalCentercAdapter
import com.manor.main.bean.MianPersonalCentercBean
import com.manor.main.bean.UserInfoBean
import com.manor.main.http.MainHttpUtil
import com.manor.main.utils.EditAvatarUtil
import com.tencent.imsdk.v2.V2TIMConversation
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.fragment_main_personalcenter.*
import okio.ByteString.Companion.toByteString
import okio.internal.commonToUtf8String
import java.io.File
import java.util.*
import com.manor.common.http.HttpSignCallback as HttpSignCallback1

/**
 * 个人中心
 * 看不懂的神仙操作，还不如不封装
 */
class MainPersonalCenterFragment : Fragment(), View.OnClickListener {

    private val lastState = 1
    private var userInfoBean: UserInfoBean? = null
    private var mImageUtil: ProcessImageUtil? = null
    private var upFile: File? = null
    private var strTotal = ""
    private var roleType = "0"


    internal var mianPersonalCentercAdapter: MianPersonalCentercAdapter? = null
    internal var personalCentercBeanList: MutableList<MianPersonalCentercBean> = ArrayList()
    private val path = arrayOf(
            RouteUtil.PC_ARISTOCRATIC_PRIVILEGE,
            RouteUtil.PC_INVITE_FRIENDS,
            RouteUtil.PC_VISITOR_RECORD,
            RouteUtil.PC_RECOMMENDED
    )
    private val pathTitle = intArrayOf(
//            StaIntentUtil.ARISTOCRATIC_PRIVILEGE,
            StaIntentUtil.INVITE_FRIENDS,
            StaIntentUtil.VISITORS_RECORD,
            StaIntentUtil.GO_TO_AUTH,
            StaIntentUtil.ONLINE_CUSTOMER
    )


    companion object {
        fun newInstance(): MainPersonalCenterFragment {
            return MainPersonalCenterFragment()
        }
    }


    @SuppressLint("HardwareIds")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        var view = inflater.inflate(R.layout.fragment_main_personalcenter, container, false)
        initView()
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initListener()
        setList()
    }


    override fun onResume() {
        super.onResume()
//        ivEntrance?.setGone("1" != CommonAppConfig.getInstance()?.config?.elvesSwitch)
        getPersonalDate()
    }

    private fun initListener() {

    }


    /**
     * 设置个人资料`
     */
    private fun getPersonalDate() {
        MainHttpUtil.getCenter(object : HttpSignCallback1() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                setInfo(code, msg, info)
                ToastUtil.show(msg)
            }
        })
    }

    @SuppressLint("SetTextI18n")
    private fun setInfo(code: Int, msg: String, info: String) {
        if (code == 0 && info != null && info.isNotEmpty()) {
            tv_pc_name?.run {
                userInfoBean = JSON.parseObject(info, UserInfoBean::class.java)
                userInfoBean?.visitor_nums_all?.let { strTotal = it }

                roleType = userInfoBean?.is_kefu?:"0"

                if (StringUtil.isNotEmpty(userInfoBean?.user_nickname)) {
                    tv_pc_name?.text = userInfoBean?.user_nickname //昵称
                }
                if (StringUtil.isNotEmpty(userInfoBean?.serial_no)) {
                    tv_user_id?.text = "淘米号：" + userInfoBean?.serial_no//ID
                } else {
                    tv_user_id?.text = "淘米号："
                }
                if (StringUtil.isNotEmpty(userInfoBean?.avatar)) {

                }

                if (StringUtil.isNotEmpty(userInfoBean?.avatar)) {
                    iv_pc_head?.run {
                        Glide.with(context)
                                .load(userInfoBean?.avatar)
                                .error(R.mipmap.default_user_icon)
                                .into(iv_pc_head)//头像
                        //   CommonAppConfig.getInstance().userBean.avatar = userInfoBean?.avatar
                    }


                }

                //判断是否是达人否认证
                if (StringUtil.isNotEmpty(userInfoBean?.isauth)) {
                    if ("1" == userInfoBean?.isauth) {
                        iv_auth?.visibility = View.VISIBLE
                        im_gz?.visibility = View.GONE
                        iv_auth?.run {
                            Glide.with(this).load(userInfoBean?.immortal).into(iv_auth)
                        }

                    } else {
                        iv_auth?.visibility = View.GONE
                    }
                }

                //判断是否是达人
                if (StringUtil.isNotEmpty(userInfoBean?.level_icon)) {
                    iv_levelicon?.visibility = View.VISIBLE
                    iv_levelicon?.run {
                        Glide.with(this).load(userInfoBean?.level_icon).into(iv_levelicon)
                    }

                } else {
                    iv_levelicon?.visibility = View.GONE
                }

                //判断是否是贵族
                if (StringUtil.isNotEmpty(userInfoBean?.gzu_icon)) {
                    iv_gzuicon?.visibility = View.VISIBLE
                    Glide.with(this).load(userInfoBean?.gzu_icon).into(iv_gzuicon)
                } else {
                    iv_gzuicon?.visibility = View.GONE
                }

                //判断是否是优质
                if (StringUtil.isNotEmpty(userInfoBean?.quality)) {
                    iv_qua?.visibility = View.VISIBLE
                    Glide.with(this).load(userInfoBean?.quality).into(iv_qua)
                } else {
                    iv_qua?.visibility = View.GONE
                }

                tv_follows?.text = userInfoBean?.follows//关注
                tv_fans?.text = userInfoBean?.fans//粉丝
                tv_black?.text = userInfoBean?.black//拉黑
                if (userInfoBean?.signature.equals("")) {
                    tv_signature?.visibility = View.GONE
                } else {
                    tv_signature?.text = userInfoBean?.signature//签名
                }

                setVisitor(userInfoBean?.visitor_nums)
            }
            iv_pc_head?.setOnClickListener(this)
            iv_pc_head?.setOnClickListener(this)
            rlCenter?.setOnClickListener(this)
            ivSetting?.setOnClickListener(this)
            ivEntrance?.setOnClickListener(this)
            ivCopy?.setOnClickListener(this)
            ClickUtils.applyPressedViewScale(ivCopy)
            ll_follows?.setOnClickListener(this)
            ll_fans?.setOnClickListener(this)
            ll_black?.setOnClickListener(this)
            tv_signature?.setOnClickListener(this)
        }

    }


    private fun setVisitor(str: String?) {
        var num = ""
        if (StringUtil.isNotEmpty(str)) {
            val count = Integer.parseInt(str)
            if (count > 0 && count <= 99) {
                num = count.toString() + ""
            } else if (count > 99) {
                num = "99+"
            }
        }
        if (mianPersonalCentercAdapter != null) {
            val pos = mianPersonalCentercAdapter?.vPos
            pos?.run {
                if (pos >= 0 && pos < personalCentercBeanList.size) {
                    personalCentercBeanList[pos].strNum = num
                    mianPersonalCentercAdapter?.notifyItemChanged(pos)
                }
            }

        }
    }

    private fun setList() {
        if (personalCentercBeanList.size > 0) {
            personalCentercBeanList.clear()
        }
//        personalCentercBeanList.add(MianPersonalCentercBean(R.mipmap.pc_guizu_x, StaIntentUtil.ARISTOCRATIC_PRIVILEGE))
        personalCentercBeanList.add(MianPersonalCentercBean(R.mipmap.pc_yaoqing, StaIntentUtil.INVITE_FRIENDS))
        personalCentercBeanList.add(MianPersonalCentercBean(R.mipmap.pc_fangke, StaIntentUtil.VISITORS_RECORD))
        personalCentercBeanList.add(MianPersonalCentercBean(R.mipmap.pc_renzheng, StaIntentUtil.GO_TO_AUTH))
        personalCentercBeanList.add(MianPersonalCentercBean(R.mipmap.pc_kefu, StaIntentUtil.ONLINE_CUSTOMER))

        rv_pc?.layoutManager = LinearLayoutManager(context)
        mianPersonalCentercAdapter = MianPersonalCentercAdapter(R.layout.rv_pc_item, personalCentercBeanList)
        rv_pc?.adapter = mianPersonalCentercAdapter
        mianPersonalCentercAdapter?.setOnItemClickListener { adapter, view, position ->
            if (ClickUtil.canClick()) {

                if (position >= pathTitle.size){
                    return@setOnItemClickListener
                }

                when (pathTitle[position]) {
                    StaIntentUtil.GO_TO_AUTH -> {
                        if (userInfoBean !=null && "1" != userInfoBean?.isauth) {
                            setCamera()
                        }else{
                            if ("1" == userInfoBean?.isauth){
                                ToastUtils.showShort("您已完成人脸认证")
                            }else{
                                ToastUtils.showShort("请稍后再试")
                            }
                        }
                    }
                    StaIntentUtil.ONLINE_CUSTOMER -> {
//                        ToastUtils.showShort("在线客服")
                        if (roleType == "1"){
                            //客服角色
                            ActivityUtils.startActivity(HMsgActivity::class.java)
                        }else{
                            //普通角色
                            val uid = "164"//administrator
                            val title = "淘米客服"
                            val avatar = ""
                            ImHttpUtil.setFriends(uid)
                            activity?.let { HChatRoomActivity.forward(it, uid, title, avatar, V2TIMConversation.V2TIM_C2C) }

                        }

                    }
                    StaIntentUtil.INVITE_FRIENDS -> {
                        RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.INVITE_FRIENDS)
                    }
                    StaIntentUtil.VISITORS_RECORD -> {
                        RouteUtil.forwardVisitor(strTotal)
                    }
                }


            }
        }
    }

    private fun setCamera() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA)//相机
                .onGranted {
                    RouteUtil.forwardFaceExp(AuthType.TYPE_AUTH)
                }
                .onDenied { data ->
                    ToastUtils.showShort(resources.getString(com.manor.paradise.R.string.permissions_camera))
                    if (AndPermission.hasAlwaysDeniedPermission(this, data)) {
                        val act = activity as AbsActivity?
                        act?.showSettingDialog(act,
                                resources.getString(com.manor.paradise.R.string.permissions_camera), 0)
                    } else {
                        setCamera()
                    }
                }
                .start()
    }



    private fun initView() {
        mImageUtil = ProcessImageUtil(activity)
        mImageUtil?.setImageResultCallback(object : ImageResultCallback {
            override fun beforeCamera() {

            }

            override fun onSuccess(file: File?) {
                if (file == null) {
                    return
                }
                upFile = file
                EditAvatarUtil.instance.uploadAvatarImage(activity, upFile, object : CommonCallback<Boolean>() {
                    override fun callback(bean: Boolean?) {
                        if (bean == true)
                            getPersonalDate()
                    }
                })


            }

            override fun onFailure() {}
        })
    }


    override fun onDestroyView() {
        super.onDestroyView()
    }


    override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_pc_head -> {
                if (ClickUtil.canClick())
                    activity?.let {
                        EditAvatarUtil.instance.editAvatar(it, this) { mediaList -> uploadAvatarImage(mediaList, false) }
                    }
            }
            R.id.rlCenter -> {
                if (ClickUtil.canClick())
                    activity?.let { UserCenterActivity.forward(it, CommonAppConfig.getInstance().uid) }
            }
            R.id.ivSetting -> {
                if (ClickUtil.canClick())
                    RouteUtil.forwardPath(RouteUtil.PC_PERSONAL_SETTINGS)
            }
            R.id.ivEntrance -> {
//                if (ClickUtil.canClick())
//                    RouteUtil.forwardElvesHome()
            }
            R.id.ivCopy -> {
                if (ClickUtil.canClick())
                    if (tv_user_id.str().isNotEmpty() && tv_user_id.str().length > 4) {
                        ToastUtil.show("复制成功")
                        ClipboardUtils.copyText(tv_user_id.str().substring(4))
                    }
            }
            R.id.ll_follows -> {
                if (ClickUtil.canClick()) {
                    FollowActivity.forward(activity, CommonAppConfig.getInstance().uid)
                }
            }
            R.id.ll_fans -> {
                if (ClickUtil.canClick()) {
                    FansActivity.forward(activity, CommonAppConfig.getInstance().uid)
                }
            }
            R.id.ll_black -> {
                if (ClickUtil.canClick()) {
                    context?.run {
                        BlackListActivity.forward(this)
                    }
                }
            }
            R.id.tv_signature -> {
                if (ClickUtil.canClick()) {
                    context?.run {
                        EdAutographActivity.forward(this, tv_signature.text.toString())
                    }
                }
            }
        }
    }


//    private val publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXP4khUyh0Du0fl6nz29X8waEqxv6Oi9E3jl1MQKyuC/Px7H3jOYZbC3ZlX+2FBYkeQKRPXI99ABNZFy5l8Ex56Bin6dnHa06zu3jjAno73xFMfk+pm7en6Vw5Y49p7On4bSD1GfNLxo3+n1LpqWtVMATjhEw7Sc+wHNgunEad2QIDAQAB";
//    private val privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJc/iSFTKHQO7R+XqfPb1fzBoSrG/o6L0TeOXUxArK4L8/HsfeM5hlsLdmVf7YUFiR5ApE9cj30AE1kXLmXwTHnoGKfp2cdrTrO7eOMCejvfEUx+T6mbt6fpXDljj2ns6fhtIPUZ80vGjf6fUumpa1UwBOOETDtJz7Ac2C6cRp3ZAgMBAAECgYAjJyE4HZvJXa6/KQDXLMEPffF3f8iqWNTHlM8aae24hg6sq8qWhUg04PUjmqgZwq+b2GpYB6tR4jKdAkZGaxNa5oJ1noALH2XDGpa62CO24pvpPZ+aeaJtsEzWu9IhJuXI35Y/+oo1eOEoomodPj1pIr97m89t4kKo8GGNvYMWAQJBAM60/zdt04gVF6FSShu8LuspV4W6jkGJAbgOkWCiHWSxh+qyZI3IUbMpHiuuxWa0C8oI9UA7fjc/UawMYitefVcCQQC7UOaHkfnQHiOgK5195IVRK4XAgEPNU6Kmo5an4yGfxItPWqw7Uws74zzlV8cUBBIAMTO5H6JsGdyB1G9qK5BPAkEAjI6fDP3tXReanePq6Lkp3laaYSDeIsobFSEy0dbqzdG6bmkn3xFcHMvU7DdHm/LKIXO98RODW+X+j1NMXdk+uQJAZh9bL7pkKhTkc2ST/pjiHjjOOP809/KLELLLZkisgkBTezYCBG3oCASBpL/QZ5c4gSZR/rHCiZEn6Rh6jbWmfQJBAK4PJL9zazh/qkQ0YiUEu1xZdo+FqXSNQu1p8HT+7H0DGyXO79IPq1EeKVER5L+OA5gdGniavcGhcVbtG0agNcg=";

//    private fun ZZTest(){
//        val zzz = "bHdYnwURXc6XfiDbgMr6V9Am0U+aACcC9ifn6071b3fOS/yRdIFl4ZajIq5bdWcPVoIs68SgcBOs8QQMxBmyp348G2BaBOCzIaHe2tWfSPr3FUZun78Eyap1xXeBdisLeazKyR4tJ1kQauZXd20G3VCesmjBZU4RE2zJrqYdUSY=";
//        val dkArr = EncodeUtils.base64Decode(privateKey.toByteArray())
//        val baseArr = EncryptUtils.decryptBase64RSA(zzz.toByteArray(), dkArr, 1024, "RSA/None/PKCS1Padding")
//        val deArr = EncodeUtils.base64Decode(baseArr)
//
//        KLog.e("ZZTest#Decrypt", "ex = ${deArr?.commonToUtf8String()}");
//
//
//        val cc = EncodeUtils.base64Encode("asdhasdasfjkasjg哈哈哈哈哈哈哈".toByteArray())
//        val ekArr = EncodeUtils.base64Decode(publicKey.toByteArray())
//        val eArr = EncryptUtils.encryptRSA2Base64(cc, ekArr, 1024, "RSA/None/PKCS1Padding")
//
//        KLog.e("ZZTest#Encrypt", " ex = ${eArr?.commonToUtf8String()}");
//
//    }


    private fun uploadAvatarImage(result: List<LocalMedia>, isBackdrop: Boolean) {
        // 图片选择结果回调
        if (result.size > 0) {
            val path = result[0].cutPath
            val file = File(path)
            upFile = file
            EditAvatarUtil.instance.uploadAvatarImage(activity, upFile, isBackdrop,
                    object : CommonCallback<Boolean>() {
                        override fun callback(bean: Boolean?) {
                            if (bean == true)
                                getPersonalDate()
                        }
                    })
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if ((requestCode == PictureConfig.CHOOSE_REQUEST || requestCode == Constants.CODE_REQUEST_BACKDROP) && resultCode == RESULT_OK) {
            // 图片选择结果回调
            val selectList = PictureSelector.obtainMultipleResult(data)
            if (selectList.size > 0) {
                val path = selectList[0].cutPath
                val file = File(path)
                upFile = file
                val isBackdrop = requestCode == Constants.CODE_REQUEST_BACKDROP

                EditAvatarUtil.instance.uploadAvatarImage(activity, upFile, isBackdrop,
                        object : CommonCallback<Boolean>() {
                            override fun callback(bean: Boolean?) {
                                if (bean!!)
                                    getPersonalDate()
                            }
                        })

            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
        } else {
            getPersonalDate()
        }
    }

    /**
     * 编辑个人资料
     */
    private fun forwardEditProfile() {
        Objects.requireNonNull<FragmentActivity>(activity).startActivity(Intent(activity, EditProfileActivity::class.java))
    }


}
